<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"
               @tree-load="treeLoad"              
               @on-load="onLoad">

      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-circle-plus-outline"
                   v-if="permission.general_org_add"
                   @click.stop="handleAddSub(scope.row)">新增子项
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   v-if="permission.general_org_batch_add"
                   @click.stop="openBatchAddDialog">批量新增
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.general_org_batch_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    <!-- 
      批量添加数据对话框
     -->
    <el-dialog title="批量导入" width='80%' :close-on-click-modal='false' :visible.sync="batchAddDialog">
      <el-tag>
 		ID，
		租户ID，
		机构号，
		机构类型，
		机构名称，
		机构全名，
		上级机构号，
		所属机构组，
		排序序号，
		是否有子节点，
		负责人ID，
		负责人名，
		机构地址，
		机构邮编号，
		联系电话号码，
		办公室编号，
		备注
      </el-tag>
      <el-input
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 20}"
        placeholder="请直接从excel粘贴内容"
        v-model="importDataArea">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleImport($event)" data-clipboard-target="#pathText">开始导入</el-button>
        <el-button size="small" @click="batchAddDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {exportGeneralOrgInfoExcel,saveOrUpdateGeneralOrgInfo,saveOrUpdateGeneralOrgInfoList,saveGeneralOrgInfo,saveGeneralOrgInfoList,deleteGeneralOrgInfo,queryGeneralOrgInfo,queryGeneralOrgTree,queryGeneralOrgInfoListPage,updateGeneralOrgInfo,deleteGeneralOrgInfoList} from '@/api/general/staff/generalOrgInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
export default {
  data() {
    return {
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        lazy:true,
        rowKey:'id',
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: false,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 220,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '机构名称',
            prop: 'orgName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            width: 240,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '机构全名',
            prop: 'orgFullName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            width: 150,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '上级机构',
            prop: 'parentOrgNo', 
            dicFlag: true,
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            width: 150,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            props: {
              label: 'orgName',
              value: 'orgNo'
            },
            type:'tree',
            dicData: [],
          }, 
          {
            label: '机构号',
            prop: 'orgNo', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            editDisabled: true,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '机构类型',
            prop: 'orgType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]             
          },
          {
            label: '负责人',
            prop: 'respsbUserName', 
            type: 'select',
            props: {
              label: 'realName',
              value: 'realName'
            },
            dicData:[],
            remote: true,
            dicMethod:'get',
            dicUrl: '/platform/sysUserInfo/querySysUserInfoListPage?optFlag=noorg&remote=yes&columnValue={{key}}&columnName=realName&tenantId='+localStorage.getItem('tenantId'),
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            // change: ({value,column}) => {
            // }, 
          },
          {
            label: '排序序号',
            prop: 'orderSeq', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            value: '1',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '机构地址',
            prop: 'orgAddress', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '机构邮编号',
            prop: 'orgPostNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '联系电话号码',
            prop: 'contactPhoneNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '办公室编号',
            prop: 'officeRoomNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '备注',
            prop: 'remark', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {parentOrgNo: '9999'}
    }
  },
  computed: {
    ...mapGetters(['website','userInfo','permission','orgTree','genOrgTree']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_org_add, false),
        viewBtn: this.vaildData(this.permission.general_org_view, false),
        delBtn: this.vaildData(this.permission.general_org_delete, false),
        editBtn: this.vaildData(this.permission.general_org_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 加载树形列表
     */
    treeLoad(tree, treeNode, resolve) {
      //this.$console.log('tree = ',tree);
      this.singleBody = {
        parentOrgNo: tree.orgNo
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: [{prop:'order_seq',order:'ascending'}],
        currentPage: 1, 
        pageSize: 100
      }
      this.commonData = reqCommonMsg(this.reqParams)
      let childrenList = [];
      queryGeneralOrgInfoListPage(this.commonData).then(res => {
        childrenList = res.data.body.listBody;
        resolve(childrenList)
      }, error => {
      });
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.data = [];
      this.loading = true;
      if(!this.singleBody.orgNo){
        this.singleBody = {parentOrgNo: this.website.orgNo.genTreeOrgNo}
      }
      this.reqParams.singleBody.belongProjectNo = this.userInfo.tenantId;
      this.orderRules = {
        order: 'ascending',
        prop: 'orderSeq'
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralOrgInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = 99999;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增子项目
     */
    handleAddSub(row){
      //this.$console.log('==row==', row) 
      this.$refs.crud.rowAdd();
      // 防止加载过快，导致失败。
      setTimeout(()=> {
        this.form.parentOrgNo = row.orgNo;
        this.form.orgType = row.orgType;
      }, 500);
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      // 解析用户名（用户ID）
      let formatUser = this.$util.formatUserName(row.respsbUserName);
      this.reqParams.singleBody.respsbUserName = formatUser.userName;
      this.reqParams.singleBody.respsbUserId = formatUser.userId;
      this.reqParams.singleBody.belongProjectNo = this.userInfo.tenantId;
      this.commonData = reqCommonMsg(this.reqParams);
      saveGeneralOrgInfo(this.commonData).then(() => {
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        this.getOrgTree();
        done();
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      if(row.orgNo == row.parentOrgNo) {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '上级机构不能是自己!'
        });
        done();
        return false;
      }
      this.reqParams.singleBody = row;
      // 解析用户名（用户ID）
      let formatUser = this.$util.formatUserName(row.respsbUserName);
      this.reqParams.singleBody.respsbUserName = formatUser.userName;
      this.reqParams.singleBody.respsbUserId = formatUser.userId;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralOrgInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        this.getOrgTree();
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralOrgInfo(this.commonData);
        })
        .then(() => {
          this.singleBody = {}
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.getOrgTree();
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      this.$refs.crud.rowView(row,row.$index);
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    // 
    handleImport() {
      this.loading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              id:field[0].trim(),
              tenantId:field[1].trim(),
              orgNo:field[2].trim(),
              orgType:field[3].trim(),
              orgName:field[4].trim(),
              orgFullName:field[5].trim(),
              parentOrgNo:field[6].trim(),
              belongOrgGroup :field[7].trim(),
              orderSeq:field[8].trim(),
              hasChildren:field[9].trim(),
              respsbUserId:field[10].trim(),
              respsbUserName:field[11].trim(),
              orgAddress:field[12].trim(),
              orgPostNo:field[13].trim(),
              contactPhoneNo:field[14].trim(),
              officeRoomNo:field[15].trim(),
              remark:field[16].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralOrgInfoList(this.commonData).then(() => {
          this.loading=false;
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.getOrgTree();
        }, error => {
          //this.$console.log(error);
          this.loading=false;
          loading();
        });      
        //this.$console.log('lineList=',dataList)
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除? 该操作将同时删除该节点下的所有子节点！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralOrgInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.getOrgTree();
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        queryGeneralOrgInfo(commonData).then(res => { 
          const column = this.findObject(this.option.column, 'respsbUserName');
          this.form = res.data.body.singleBody;
          this.form.respsbUserName = res.data.body.singleBody.respsbUserName+'('+ res.data.body.singleBody.respsbUserId +')';
        });
      }
      done();
    },
    
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralOrgInfoExcel(this.commonData);
    },
    /**
     * 获取树形菜单
     */
    getOrgTree(){
      // 加载树形机构列表
      this.singleBody = {
        orgNo: this.website.orgNo.genTreeOrgNo
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralOrgTree(this.commonData).then(res => {
        this.singleBody = {};
        this.$store.dispatch('setGenOrgTree', res.data.body.listBody)
        const column = this.findObject(this.option.column, 'parentOrgNo');
        column.dicData = [];
        column.dicData =  this.deepClone(res.data.body.listBody); 
        column.dicData.push({
          orgNo: this.website.orgNo.genTreeOrgNo,
          orgName: '根节点(0000)'
        })
      }, error => {
      });
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["orgType"]');
      this.findObject(this.option.column, 'orgType').dicData = dicData.orgType;
    }
  },
  
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalOrgInfoColumn'});
    setTimeout(() => {
      this.getOrgTree();
      this.getBizDict();
    }, 100);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalOrgInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalOrgInfoColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
 .breadcrumb{
   padding-bottom:20px;
 }
</style>